package com.ship.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.auth.entity.bo.AuthenticationTokenBo;
import com.ship.auth.entity.vo.AuthenticationUserVo;
import com.ship.auth.entity.vo.RegisterVo;
import com.ship.auth.service.AuthenticationService;
import com.ship.auth.service.SysLoginService;
import com.ship.auth.uitl.AuthenticationUtil;
import com.ship.common.redis.configure.RedisRepository;
import com.ship.common.redis.service.RedisService;
import com.ship.system.api.RemoteUserService;
import com.ship.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class AuthenticationServiceImpl implements AuthenticationService {
    @Autowired
    public AuthenticationUtil authenticationUtil;
    @Autowired
    protected RestTemplate restTemplate;
    @Resource
    private SysLoginService loginService;
    @Autowired
    private RedisService redisService;

    /**
     * 获取认证统一登录
     *
     * @return
     */
    public String authenticationLogin(String type) {
        String baseUrl = String.format("?state=%s&response_type=%s&client_id=%s&redirect_uri=%s",type, authenticationUtil.responseType,
                authenticationUtil.clientId,authenticationUtil.redirectUrl);
        String url = authenticationUtil.authenLoginUrl + baseUrl;
        return url;
    }

    /**
     * 通过授权码接口返回地址，获取token
     * @param code
     * @param state
     */
    public AuthenticationUserVo getAuthenticationToken(String code, String state) {
        Boolean judge = false;
        String url = authenticationUtil.tokenUrl;

        // 请求头设置,x-www-form-urlencoded格式的数据
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        //提交参数设置
//        url = String.format(url+"?client_id=%s&client_secret=%s&code=%s&grant_type=%s",authenticationUtil.clientId,authenticationUtil.secretKey,code,authenticationUtil.grantType);
        url = String.format(url+"?code=%s&grant_type=%s&client_id=%s&client_secret=%s",code,authenticationUtil.grantType,authenticationUtil.clientId,"a1f62e946bf4425b937a8049893fc066");//测试环境
//        url = String.format(url+"?code=%s&grant_type=%s&client_id=%s&client_secret=%s",code,authenticationUtil.grantType,authenticationUtil.clientId,"81358aaec5b7455384bdee92f41e5025");//生产环境
        System.out.println("getAuthenticationToken中的 url："+url);
        // 发送post请求，并打印结果，以String类型接收响应结果JSON字符串
        Object result = restTemplate.postForObject(url, Object.class,String.class);
        System.out.println("getAuthenticationToken方法返回值:"+result.toString());

//        Map<String,Object> reqmap = ((Map<String,Object>) JSON.parse((String) result));
        JSONObject jsonObject =  JSONObject.parseObject(result.toString());
        System.out.println(((Map<?, ?>) JSON.parse((String) result)).get("expires_in"));
        String expiresIn = jsonObject.getString("expires_in");
        String accessToken = jsonObject.getString("access_token");
        System.out.println("getAuthenticationToken中的 accessToken："+accessToken);

        String refreshToken = jsonObject.getString("refresh_token");
        String uid = jsonObject.getString("uid");
        System.out.println("getAuthenticationToken中的 uid："+uid);



//        String expiresIn = ((LinkedHashMap) result).get("expires_in").toString();
//        String accessToken = ((LinkedHashMap) result).get("access_token").toString();
//        String refreshToken = ((LinkedHashMap) result).get("refresh_token").toString();
//        String uid = ((LinkedHashMap) result).get("uid").toString();

//        if(StringUtils.isEmpty(uid)){
//            String errcode = ((LinkedHashMap) result).get("errcode").toString();
//            String msg = ((LinkedHashMap) result).get("uid").toString();
//        }

        AuthenticationTokenBo authenticationTokenBo = new AuthenticationTokenBo();
        authenticationTokenBo.setAccessToken(accessToken);
        authenticationTokenBo.setRefreshToken(refreshToken);
        authenticationTokenBo.setUid(uid);
        authenticationTokenBo.setExpiresIn(expiresIn);
        try {
            state =  URLEncoder.encode(state,"UTF-8");
            authenticationTokenBo.setState(state);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取用户信息
        AuthenticationUserVo authenticationUserVo = getUserInfo(authenticationTokenBo.getAccessToken(),authenticationTokenBo.getUid());

        LoginUser loginUser = loginService.authenticationLogin(authenticationUserVo.getLoginName());
        authenticationUserVo.setToken(loginUser.getToken());
        authenticationUserVo.setUsername(authenticationUserVo.getLoginName());

//        if(StringUtils.isNotEmpty(authenticationUserVo.getLoginName())){
//            String tokenRedis = redisService.getCacheObject(authenticationUserVo.getLoginName());
//            if(StringUtils.isEmpty(tokenRedis)){
//                redisService.setCacheObject(authenticationUserVo.getLoginName(),accessToken);
//                judge =true;
//            }else{
//                if(!tokenRedis.equals(accessToken)){
//                    judge = false;
//                }
//            }
//        }

        authenticationUserVo.setJudge(judge);

        return authenticationUserVo;
    }

    /**
     * 获取统一身份验证-----用户信息
     * @param accessToken
     * @return
     */
    @Override
    public AuthenticationUserVo getUserInfo(String accessToken,String uid) {
        System.out.println("进入getUserInfo");
        String url = authenticationUtil.userInfoUrl;
        url = String.format(url+"?access_token=%s&client_id=%s",accessToken,authenticationUtil.clientId);

        Object result = restTemplate.getForObject(url, Object.class);
        System.out.println("打印result");
        System.out.println(result);
//        JSONObject jsonObject =  JSONObject.parseObject(result.toString());
        Object object = JSONObject.toJSON(result);

//        System.out.println("getUserInfo方法返回值:"+jsonObject.toString());
//
//        String errcode = jsonObject.getString("errcode");
//        String msg = jsonObject.getString("msg");
//        String loginName = jsonObject.getString("loginName");
//        String spRoleList = jsonObject.getString("spRoleList");

//        String errcode = ((LinkedHashMap) result).get("errcode").toString();
//        String msg = ((LinkedHashMap) result).get("msg").toString();
        String loginName = ((LinkedHashMap) result).get("loginName").toString();
        String spRoleList = ((LinkedHashMap) result).get("spRoleList").toString();

        AuthenticationUserVo authenticationUserVo = new AuthenticationUserVo();
        authenticationUserVo.setLoginName(loginName);
        if(StringUtils.isNotBlank(spRoleList)){
            authenticationUserVo.setSpRoleList(Arrays.asList(spRoleList));
        }

        //通过AuthenticationUserVo 新增用户信息
        //需要判断一下用户是否存在
//        User user = new User();
//
//        userService.save(user);
        RegisterVo registerVo = new RegisterVo();
        registerVo.setUserName(loginName);
//        registerVo.setPassword(password);
//        registerVo.setBimRemotePwd(bimRemotePwd);
//        registerVo.setBimRemoteUser(bimRemoteUser);
//
//        String uid = userCreateService.addUser(registerVo);

        return authenticationUserVo;
    }

}
